import axios from 'axios'
import Qs from 'qs'
import router from '@/router/index'
import { Notification } from 'element-ui';
import Util from '@/libs/util'

axios.defaults.timeout = 10000;
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
axios.interceptors.request.use(
	config => {
		let token = Util.getStore('token') ? Util.getStore('token') : null
		config.headers.common['Accept'] = 'application/json';
		let url = config.url.toLowerCase()
		if(token && url.indexOf('login') === -1) {
			config.headers.common['Authorization'] = `${token}`
		}
		return config;
	},
	err => {
		return Promise.reject(err);
	})
axios.interceptors.response.use(
	response => {
		return response;
	},
	error => {
		if(error.response) {
			switch(error.response.status) {
				case 401:
					router.replace({
						path: '/login',
						query: {
							redirect: router.currentRoute.fullPath
						}
					})
			}
		}
		return Promise.reject(error.response.data) // 返回接口返回的错误信息
	});

const GetToURL = payload => {
	let dataStr = '?';
	Object.keys(payload).forEach(key => {
		dataStr += key + '=' + payload[key] + '&';
	})
	if(dataStr !== '') {
		dataStr = dataStr.substr(0, dataStr.lastIndexOf('&'));
	}
	return encodeURI(dataStr)
}

const formatQSString = (json) => {
	return	Object.keys(json).map(function(key) {
			return encodeURIComponent(key) + '=' +
				encodeURIComponent(json[key]);
		}).join('&');
}

const showError = (msg)=>{
  Notification.error({
    title: '错误',
    message: msg? msg : '服务端接口错误，请联系管理员',
    duration: 1500
  });
}

export default async(type = 'GET', url, data = {}) => {
	type = type.toUpperCase()
	let prefix = ''
	url.indexOf('?') > -1 ? prefix = '&' : prefix = '?'
	if(type == 'GET') {
		let fullurl = url + GetToURL(data)
		return new Promise((resolve, reject) => {
			axios.get(fullurl).then(response => {
				if(url.indexOf('wsMapData') > -1){
					resolve(response.data)
					return false
				}
				if(response.status == 200) {
					if(response.data.code === 0) {
						resolve(response.data.data)
					} else if(response.data.code === 99 || response.data.code === 98) {
							router.replace({
								path: '/login',
								query: {
									redirect: router.currentRoute.fullPath
								}
							})
					} else {
            showError(response.data.msg)
            reject(response.data.msg)
          }
				} else {
					showError(response.data.msg)
					reject('HTTP ERROR')
				}
			}).catch(error => {
				if(url.indexOf('wsMapData') > -1){
					resolve([])
				} else {
					reject('ERROR')
					showError(error)
				}
				
			})
		})
	}

	if(type == 'POST') {
		return new Promise((resolve, reject) => {
			let qsstring = null
			if(url == '/apis/tile/reloadGroupTiles'){
				qsstring = data
			} else {
				qsstring = Qs.stringify(data)
			}
			axios.post(url, qsstring ).then(response => {
				if(response.status == 200) {
					if(response.data.code === 0) {
						resolve(response.data)
					} else if(response.data.code === 401) {
            router.replace({
              path: '/login',
              query: {
                redirect: router.currentRoute.fullPath
              }
            })
        } else {
          showError(response.data.msg)
          reject(response.data.msg)
        }
				} else {
          showError(response.data.msg)
					reject('HTTP ERROR')
				}
			}).catch(error => {
				showError(error)
			})
		})
	}
}